<template>
	<view class="search_wrap">
		<view class="search_box">
			<text class="iconfont icon-sousuo search-icon"></text>
			<input type="text" focus @input="handleSearchKey" v-model.lazy="key" class="search-input"
				placeholder-class="placeholder" :placeholder="defaultKey + ' 最近很火哦!'" />
			<text class="iconfont icon-quxiao1 cancel-icon" @click="clearKey"></text>
		</view>
		<view class="search_info" v-if="flag && !isShow">
			<view class="nav_box">
				<view v-for="(nav, index) of searchNav" @click="changeNav(nav.type, index)" class="nav-item"
					:key="nav.type">
					<text :class="curIndex === index?'actived':''">{{nav.text}}</text>
				</view>
			</view>
			<swiper circular @animationfinish="changeItem" :current="curIndex" class="swiper-box">
				<swiper-item v-for="index of searchNav.length" :key="index">
					<scroll-view scroll-y @scrolltolower="scrolltolower">
						<view class="scroll-item" v-for="(item, index) in searchInfo" :key="index">
							<view v-if="curIndex === 0 && item.artists" @click="toMusicPlayer(item, index)" class="song">
								<view class="scroll-item_name text_ellipsis">{{item.name}}</view>
								<view class="scroll-item_info">
									<text>{{item.artists[0].name}}</text>
									-
									<text>{{item.album.name}}</text>
								</view>
							</view>
							<view v-else-if="curIndex === 1 && item.creator" class="song_list" @click="toPlayList(item.id)">
								<image :src="item.coverImgUrl"></image>
								<view class="right_info">
									<view class="right_info_name">{{ item.name }}</view>
									<view class="right_info_detail">
										{{item.trackCount}}首,by {{ item.creator.nickname }},播放{{ item.playCount }}次
									</view>
								</view>
							</view>
							<view v-else-if="curIndex === 2" class="video_box"
								:class="(index === searchInfo.length - 1) ? 'none' : ''">
								<view class="video_name">{{ item.title }}</view>
								<image :src="item.coverUrl" @click="toVideoPlayer(item.vid, item.type)"></image>
							</view>
						</view>
						<view class="tip" v-if="!hasMore">
							没有更多数据了...
						</view>
					</scroll-view>
				</swiper-item>
			</swiper>
		</view>
		<template v-else>
			<template v-if="!key">
				<view class="history-search-key" v-if="historyKeyList.length">
					<text>历史</text>
					<scroll-view scroll-x>
						<view class="scroll-view-content">
							<view class="scroll-view-item text_ellipsis" @click="toSearch(item)" v-for="(item, index) in historyKeyList" :key="index">{{item}}</view>
						</view>
					</scroll-view>
					<text class="iconfont icon-quxiao1" @click="clearHisKey"></text>
				</view>
				<view class="search-hot" v-if="hotSearch.length">
					<view class="search-hot-title">热搜榜</view>
					<view class="hot">
						<!-- 这里直接传入 item.searchWord,在微信小程序中获取不到 undefined, H5正常显示,可能是 key值不存在导致的,因为key值必须唯一且存在-->
						<view class="hot-item text_ellipsis" v-for="(item, index) in hotSearch" :key="index" @click="toSearch(item.searchWord)" >
							<view class="text_ellipsis" style="padding: 0 10rpx;">
								<text class="hot-item-index">{{index+1}}</text>
								<text class="hot-item-name">{{item.searchWord}}</text>
								<image v-if="item.iconType" :src="item.iconUrl" class="hot-icon"></image>
							</view>
						</view>
					</view>
				</view>
			</template>
		</template>
		<view class="suggest_list" v-if="key && isShow">
			<view class="suggest_list-item text_ellipsis" @click="toSearch(item.keyword)"
				v-for="(item, index) in searchSuggestList" :key="index">
				<text class="iconfont icon-wangyiyunyinle-copy"></text>
				<text>{{item.keyword}}</text>
			</view>
		</view>
		<BottomBar ref="btmBarRef" />
	</view>
</template>

<script>
	import BottomBar from '../index/childComps/BottomBar.vue'
	import {
		getSearchDefault,
		getHotSearch,
		getSearchInfo,
		getSearchSuggest
	} from '../../api/index.js'
	// 状态位valid来表示当前函数是否处于工作状态 let valid = true
	let valid = true // true不处于,false反之
	export default {
		data() {
			return {
				// 用户输入的key
				key: '',
				// 用户默认搜索的key
				defaultKey: '',
				// 搜索建议列表
				searchSuggestList: [],
				// 搜索后的数据列表
				searchInfo: [],
				// 当前type值[用于切换 searchNav ]
				curIndex: 0,
				// 判断是否已经进入了搜索详情页面
				flag: false,
				// 热搜榜数据
				hotSearch: [],
				isShow: true,
				// 当前所在swiper项的type值
				type: 1,
				// 判断是否还有下一页数据
				hasMore: true,
				searchNav: [{
					type: 1,
					text: '单曲'
				}, {
					type: 1000,
					text: '歌单'
				}, {
					type: 1014,
					text: '视频'
				}],
				// 用户输入过的历史key列表
				historyKeyList: uni.getStorageSync('historyKeyList') || []
			}
		},
		components: {
			BottomBar
		},
		onLoad() {
			this.getSearchDefaultFun()
			this.getHotSearchFun()
		},
		watch: {
			type(newType) {
				// 切换时先清空上一个type的数据
				this.searchInfo = []
				this.hasMore = true
				this.getSearchInfoFun(this.key, newType)
			}
		},
		methods: {
			// 获取默认的搜索关键词
			async getSearchDefaultFun() {
				const {
					data: {
						data: res
					}
				} = await getSearchDefault()
				// 存储默认key
				this.defaultKey = res.showKeyword
			},
			// 获取热搜榜数据
			async getHotSearchFun() {
				const {
					data: {
						data: res
					}
				} = await getHotSearch()
				this.hotSearch = res
			},
			// 根据用户输入的key值,给出搜索建议
			async getSearchSuggestFun(keywords) {
				const res = await getSearchSuggest({
					keywords,
					type: 'mobile'
				})
				this.searchSuggestList = [...res.data.result.allMatch]
			},
			// 获取根据用户输入的key请求到的数据
			async getSearchInfoFun(keywords, type = 1, offset = '') {
				const {
					data: {
						result: res
					}
				} = await getSearchInfo({
					keywords,
					limit: 21,
					offset,
					type
				})
				// 获取有没有很多数据的标识
				this.hasMore = res.hasMore
				this.isShow = false
				if (!res.hasMore) return
				// 进行数据的分类
				switch (type) {
					case 1:
						this.searchInfo.push(...res.songs)
						break;
					case 1000:
						this.searchInfo.push(...res.playlists)
						break;
					case 1014:
						this.searchInfo.push(...res.videos)
						console.log(this.searchInfo)
						break;
				}
			},
			// 节流函数
			throttle(fn, delay, key) {
				// 运用了节流技术
				if (!valid) {
					// 休息时间,不触发
					return false
				}
				// 工作时间,把状态设置为无效,并执行回调
				valid = false
				setTimeout(() => {
					fn(key)
					valid = true
				}, delay)
			},
			// 点击清除用户输入的key
			clearKey() {
				/* 重置数据 */
				this.key = ''
				this.flag = false
				// 同时清除搜索建议
				this.searchSuggestList = []
				this.searchInfo = []
				this.curIndex = 0
			},
			// 点击清除用户输入过的历史key列表
			clearHisKey() {
				this.historyKeyList = []
				// 去除本地历史key列表
				uni.removeStorageSync('historyKeyList')
			},
			// 用户输入时触发
			handleSearchKey(e) {
				const {
					value: key
				} = e.detail
        this.key = key
				if (!key) {
					this.searchSuggestList = []
					this.flag = false
					this.curIndex = 0
					this.isShow = false
					return
				}
				this.isShow = true
        console.log(this.isShow)
				// 使用全局节流函数来触发获取搜索建议数据方法
				// this.getSearchSuggestFun(key)
				this.throttle(this.getSearchSuggestFun, 1000, key)
			},
			//用户点击某个热搜榜item项或建议项或历史项时触发
			toSearch(keywords) {
				if (!keywords) return
				this.key = keywords
				// 存储为历史项及去除重复项
				if (this.historyKeyList.indexOf(keywords) === -1) {
					this.historyKeyList.push(keywords)
					// 更新本地的历史搜索列表
					uni.setStorageSync('historyKeyList', this.historyKeyList)
				}
				this.flag = true
				this.getSearchInfoFun(keywords)
			},
			// 点击切换nav时触发
			changeNav(type, index) {
				this.curIndex = index
				this.type = type
			},
			changeItem(e) {
				const { current } = e.detail
				this.curIndex = current
				this.type = this.searchNav[current].type
			},
			// 上拉加载更多
			scrolltolower() {
				this.getSearchInfoFun(this.key, this.type, this.searchInfo.length)
			},
			// 点击推荐歌曲某一项时触发
			toPlayList (playListId) {
				uni.navigateTo({
					url: '/pages/playlist/playlist?playListId=' + playListId
				})
			},
			// 跳转到musicplayer页面
			toMusicPlayer(item) {
				let curIndex = uni.getStorageSync("curIndex")
				const { id, album, artists, name } = item
				let flag = false
				// 获取到本地的音乐列表
				const musicPlaylist = uni.getStorageSync('musicPlaylist')
				// 去除重复
				/** 
				 * entries() 方法返回一个数组的迭代对象，该对象包含数组的键值对 (key/value)。
				 * 迭代对象中数组的索引值作为 key， 数组元素作为 value。
				  * */
				for(let [i, value] of musicPlaylist.entries()) {
					if (value.id == item.id) {
						flag = false
						// 相同则调到对应的位置去>
						curIndex = i
						break
					} else {
						flag = true
					}
				}
				if (flag) {
					// 音乐列表中没有用户点击的音乐
					musicPlaylist.splice(curIndex, 0, { al: {id: album.id, name: album.name, picUrl: album.artist.img1v1Url}, ar: artists, id, name })
					// 更新本地的音乐列表
					uni.setStorageSync('musicPlaylist', musicPlaylist)
					// 更新store中的播放列表
					this.$store.commit('CHANGEMUSICPLAYLIST', musicPlaylist)
				}
				// cur_index: 当前用户点击的音乐在列表中的索引值
				uni.navigateTo({
					url: `/pages/musicplayer/musicplayer?id=${id}&cur_index=${curIndex}&flag=1`
				 });
			},
			// 跳转到视频播放页面
			toVideoPlayer(id,type) {
				uni.navigateTo({
					url: '/pages/videoplayer/videoplayer?id=' + id + '&type=' + type
				})
			}
		},
		onShow() {
			// 等待DOM加载完毕后在执行，子组件 BottomBar的初始化数据函数
			this.$nextTick(function(){
				this.$refs.btmBarRef.initData()
			})
		}
	}
</script>

<style lang="scss" scoped>
	.search_wrap {
		.search_box {
			background-color: #dc2c1f;
			display: flex;
			align-items: center;
			padding: 20rpx;

			.search-icon {
				font-size: 60rpx;
				color: white;
			}

			.search-input {
				flex: 1;
				margin: 0 20rpx;
				border-bottom: 1px solid white;
				padding-left: 10rpx;
				font-size: 28rpx;
				// 单独设置光标颜色
				caret-color: #feeeed;
				color: white;

				&.placeholder {
					color: #90a4ae;
				}
			}

			.cancel-icon {
				color: white;
			}
		}

		// 搜索信息
		.search_info {

			// nav区域
			.nav_box {
				padding-top: 40rpx;
				display: flex;
				background-color: #dc2c1f;

				.nav-item {
					flex: 1;
					text-align: center;

					>text {
						display: inline-block;

						&.actived {
							color: white;
							border-bottom: 7rpx solid white;
						}
					}
				}
			}

			.swiper-box {
				width: 100vw;
				/* #ifndef H5 */
				height: calc(100vh - 300rpx);
				/* #endif */
				/* #ifdef H5 */
				height: calc(100vh - 400rpx);
				/* #endif */
				// 滚动区域
				scroll-view {
					width: 100%;
					height: 100%;
					padding: 10rpx 20rpx;
					box-sizing: border-box;

					.scroll-item {
						padding: 10rpx;

						// 单曲样式
						.song {
							.scroll-item_name {
								font-size: 30rpx;
							}

							.scroll-item_info {
								margin-top: 5rpx;
								font-size: 25rpx;

								>text:first-child {
									color: #66d9ef;
								}

								>text:last-child {
									color: #acacac;
								}
							}
						}

						// 歌单样式
						.song_list {
							display: flex;
							padding: 10rpx 0;

							image {
								width: 100rpx;
								height: 100rpx;
								border-radius: 20rpx;
								margin-right: 15rpx;
                /* #ifdef APP-PLUS */
                background: url('@/static/images/song/default.png') no-repeat center center;
                background-size: cover;
                /* #endif */
							}

							.right_info {
								display: flex;
								flex-direction: column;
								justify-content: space-between;

								.right_info_name {
									font-weight: 520rpx;
									font-size: 30rpx;
								}

								.right_info_detail {
									font-size: 26rpx;
									color: #C8C7CC;
								}
							}
						}

						// 视频样式
						.video_box {
							padding-bottom: 30rpx;
							border-bottom: 1px solid #C8C7CC;

							&.none {
								&:last-child {
									border-bottom: 0;
								}
							}

							.video_name {
								text-align: center;
								margin-bottom: 20rpx;
							}

							image {
								width: 100%;
								border-radius: 30rpx;
							}
						}
					}
				}
			}
		}

		// 历史
		.history-search-key {
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 20rpx;
			white-space: nowrap;

			text {
				font-weight: bold;
				display: block;
			}

			scroll-view {
				width: calc(100% - 16vw);
				white-space: nowrap;
				margin: 0 15rpx;

				::-webkit-scrollbar {
					display: none;
				}

				.scroll-view-content {
					display: flex;
					width: 100%;

					.scroll-view-item {
						background-color: rgba(144, 164, 174, 0.05);
						width: 150rpx;
						min-width: 150rpx;
						height: 60rpx;
						padding: 0 5rpx;
						line-height: 60rpx;
						text-align: center;
						border-radius: 30rpx;
					}
				}
			}
		}

		.suggest_list {
			padding: 0 20rpx;

			.suggest_list-item {
				height: 100rpx;
				padding-left: 28rpx;
				line-height: 100rpx;
				border-bottom: #C8C7CC solid 1px;

				text:last-child {
					font-size: 30rpx;
					margin-left: 15rpx;
				}
			}
		}

		.search-hot {
			padding: 0 20rpx;

			.search-hot-title {
				font-weight: bold;
				font-size: 30rpx;
				padding-left: 10rpx;
				line-height: 70rpx;
				border-bottom: 1px solid #C8C7CC;
			}

			.hot {
				padding: 30rpx;
				margin: 0 auto;
				display: flex;
				flex-wrap: wrap;

				.hot-item {
					width: 50%;
					height: 80rpx;
					line-height: 80rpx;

					.hot-item-index {
						color: red;
						font-weight: 550;
						margin-right: 15rpx;
					}

					.hot-icon {
						width: 30rpx;
						height: 20rpx;
						margin-left: 15rpx;
						transform: translateY(-55%);
					}
				}
			}
		}
	}
</style>
